package jfood.chef;

import java.util.ArrayList;

import jade.content.lang.Codec;
import jade.content.lang.sl.SLCodec;
import jade.content.onto.Ontology;
import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.Property;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jfood.chef.DatabaseWriter;
import jfood.ontology.meal.Meal;
import jfood.ontology.meal.MealOntology;
import jfood.ontology.query.QueryOntology;
import jfood.parser.CoJemyParser;

public class ChefAgent extends Agent {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7083856170164490981L;
	private static final String SERVICE_NAME = "Chef";

	private Codec codec = new SLCodec();
	private Ontology mealOntology = MealOntology.getInstance();
    private Ontology queryOntology = QueryOntology.getInstance();
    private DatabaseWriter databaseHandler;
    
        
	private void registerService() {
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(getAID());
		ServiceDescription sd = new ServiceDescription();
		sd.setName(SERVICE_NAME);
		sd.setType("meal-knowledge");
		sd.addOntologies(MealOntology.NAME);
		sd.addOntologies(QueryOntology.NAME);
		sd.addLanguages(FIPANames.ContentLanguage.FIPA_SL);
		sd.addProperties(new Property("country", "Poland"));
		dfd.addServices(sd);
		
		try {
			DFService.register(this, dfd);
		} catch (FIPAException e) {
			System.err.println(getLocalName()
					+ " registration with DF unsucceeded. Reason: "
					+ e.getMessage());
			doDelete();
		}
	}

	protected void setup() {
//		String databasePath = "test.pro";
		String databasePath = getLocalName()+".pro";
		databaseHandler = new DatabaseWriter(databasePath);
		
		System.out.println(this.getLocalName()+ ": Barman setup");
		CoJemyParser parser = new CoJemyParser();//CoJemyParser.getParser(this.getLocalName());
		
		if (parser == null)
		{
			System.out.println(this.getLocalName() +":There is no knowledge connected to chef, name: " +this.getLocalName() );
			System.out.println(this.getLocalName() +":Destroying chef");
			doDelete();
		}
		else
		{
			System.out.println(this.getLocalName() +":Chef getting data from " + this.getLocalName());
			if (!databaseHandler.databaseExists())
			{
				ArrayList<Meal> meals = parser.parse();
				
				int i = 0;
				for (Meal meal : meals) {
					System.out.println(meal);
					System.out.println(i++);
				}
				
				databaseHandler.writeMeals(meals);
			}
			getContentManager().registerLanguage(codec);
			getContentManager().registerOntology(mealOntology, MealOntology.NAME);
			getContentManager().registerOntology(queryOntology, QueryOntology.NAME);
			registerService();
			addBehaviour(new WaitForOrdersBehaviour(databasePath));
		}
	}
}
